package com.wu.foodsafetyplayer.http;

import android.os.Handler;
import android.os.Looper;
import android.util.Log;

import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.WebSocket;
import okhttp3.WebSocketListener;

public class WebSocketClient {
    public static final String TAG = WebSocketClient.class.getSimpleName();
    public static boolean isRuning = false;

    /**
     * WebSocket长连接
     *
     * @param url
     * @param handle
     * @return
     */
    public static WebSocket start(String url, final DisposeDataHandle handle) {
        final Handler mDeliveryHandler = new Handler(Looper.getMainLooper());
        OkHttpClient mClient = new OkHttpClient.Builder().pingInterval(10, TimeUnit.SECONDS).build();
        Request request = new Request.Builder().url(url).build();

        WebSocket mWebSocket = mClient.newWebSocket(request, new WebSocketListener() {
            @Override
            public void onClosed(@NotNull WebSocket webSocket, int code, @NotNull final String reason) {
                super.onClosed(webSocket, code, reason);
                mDeliveryHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        Log.e(TAG, "onClosed-----" + reason);
                        isRuning = false;
                        handle.mListener.onFailure(new OkHttpException(-1, reason));
                    }
                });
            }

            @Override
            public void onFailure(@NotNull WebSocket webSocket, @NotNull Throwable t, @Nullable final Response response) {
                super.onFailure(webSocket, t, response);
                mDeliveryHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        Log.e(TAG, "onFailure-----" + response);
                        isRuning = false;
                        handle.mListener.onFailure(new OkHttpException(-1, response));
                    }
                });
            }

            @Override
            public void onMessage(@NotNull WebSocket webSocket, @NotNull final String text) {
                super.onMessage(webSocket, text);
                mDeliveryHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        Log.e(TAG, "onMessage-----" + text);
                        isRuning = true;
                        handle.mListener.onSuccess(text);
                    }
                });
            }

            @Override
            public void onOpen(@NotNull WebSocket webSocket, @NotNull Response response) {
                super.onOpen(webSocket, response);
                Log.e(TAG, "onOpen-----" + response);
            }
        });


        return mWebSocket;
    }
}
